
#include "test_util.h"
#include <cassert>
#include <cstdio>
#include <cstring>
#include <fcntl.h>
#include <netinet/in.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <errno.h>
#include <netdb.h>
#include <string>
#include <sys/socket.h>

int CreateClientSocket()
{
    std::string hostname = "www.baidu.com";
    std::string protocol = "http";
    struct addrinfo hints;
    memset(&hints, 0, sizeof(hints));
    hints.ai_family   = AF_INET;
    hints.ai_flags    = 0;
    hints.ai_socktype = SOCK_STREAM;
    struct addrinfo * result = nullptr;
    int res = getaddrinfo(hostname.c_str(), protocol.c_str(), &hints, &result);
    if (res >= 0)
    {
        for (struct addrinfo * ptr = result; ptr; ptr = ptr->ai_next)
        {
            struct sockaddr * sa = ptr->ai_addr;
            if (ptr->ai_family == AF_INET)
            {
                /* struct sockaddr_in * sai = (struct sockaddr_in*)sa; */
                int socket_fd = socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol);
                if (socket_fd >= 0)
                {
                    int connect_result = connect(socket_fd, sa, ptr->ai_addrlen);
                    if (connect_result >= 0)
                    {
                        freeaddrinfo(result);
                        int flags = fcntl(socket_fd, F_GETFL);
                        fcntl(socket_fd, F_SETFL, flags | O_NONBLOCK);
                        return socket_fd;
                    }
                    else
                    {
                        printf("connect server ip : %s failed errno : %d.\n", hostname.c_str(), errno);
                    }
                }
            }
        }
    }
    if (result)
    {
        freeaddrinfo(result);
    }
    return 0;
}

int CreateServerSocket()
{
    int server_socket = socket(AF_INET, SOCK_STREAM, 0);
    if (server_socket >= 0)
    {
        struct sockaddr_in sai;
        memset(&sai, 0, sizeof(sai));
        sai.sin_family = AF_INET;
        sai.sin_port   = htons(8099);
        sai.sin_addr.s_addr = htonl(INADDR_ANY);

        assert(bind(server_socket, (struct sockaddr*)&sai, sizeof(sai))==0);

        int flags = fcntl(server_socket, F_GETFL);
        fcntl(server_socket, F_SETFL, flags | O_NONBLOCK);

        listen(server_socket, 100);
        return server_socket;
    }
    return 0;
}




